package com.weilive.platform;

import java.io.File;
import java.util.concurrent.ConcurrentLinkedQueue;

import com.weilive.core.common.SharedFileMonitor;
import com.weilive.core.common.SharedTimer;
import com.weilive.core.utils.FileMonitor.Listener;
import com.weilive.core.utils.FileUtils;
import com.weilive.core.utils.MailSender;
import com.weilive.core.utils.PropertiesFile;

public class PlatformMail {

	public static class Mail {
		public final String recipient;
		public final String subject;
		public final String content;

		public Mail(String recipient, String subject, String content) {
			this.recipient = recipient;
			this.subject = subject;
			this.content = content;
		}
	}

	private final static String PROPERTIES_FILE = "mail.properties";
	private final static long EMAIL_SEND_INTERVAL = 1 * 1000;
	private static String forgetPwdHost = "";

	private static MailSender mailSender = null;
	private static ConcurrentLinkedQueue<Mail> mails = new ConcurrentLinkedQueue<Mail>();

	static {
		reloadData();
		// 文件监听
		SharedFileMonitor.listen(FileUtils.getResourcePath(PROPERTIES_FILE),
				new Listener() {
					@Override
					public void onModifyFile(File file) {
						reloadData();
					}
				});
		// 定时任务
		SharedTimer.schedule(new Runnable() {

			@Override
			public void run() {
				Mail mail = mails.poll();
				if (mail != null) {
					try {
						mailSender.send(mail.recipient, mail.subject,
								mail.content);
					} catch (Exception e) {
						e.printStackTrace();
					}
				}
			}
		}, EMAIL_SEND_INTERVAL, EMAIL_SEND_INTERVAL);
	}

	private static void reloadData() {
		PropertiesFile properties = new PropertiesFile(
				FileUtils.getResourcePath(PROPERTIES_FILE));
		forgetPwdHost = properties.get("password.forget.host");
		String smtpHostName = properties.get("mail.host.name");
		int smtpHostPort = properties.getInt("mail.host.port", 25);
		String username = properties.get("mail.user.name");
		String password = properties.get("mail.user.password");
		mailSender = new MailSender(smtpHostName, smtpHostPort, username,
				password);
	}

	public static String getForgetPasswordHost() {
		return forgetPwdHost;
	}

	public static void sendMail(Mail mail) {
		if (mail != null) {
			mails.add(mail);
		}
	}
}
